from unittest import result
from models.ios_widget import model
from datetime import datetime, timedelta

tb_analysis_user_data = model.AnalysisUserWidgetList()
tb_module = model.ComponentLibraryModuleList()


def format_data(f):
    # 格式化分析数据
    keys = ['oid', 'widget_type', 'thumb_url', 'view_count', 'view_count_user', 'click_count', 'click_count_user',
           'complete_set_count', 'complete_set_count_user', 'click_rate', 'complete_set_rate', 'atime']
    r = {k:f[k] for k in keys if k in f}
    return r

def get_rate_pencent(up, down):
    rate = (up/down)*100
    r = f"{rate:.2f}%"
    return r

def get_data(result_list:list=None, skip:int=0, limit:int=0, start_date:datetime=None, end_date:datetime=None):
    if start_date:
        if end_date:
            start_time = start_date
            end_time = end_date
        else:
            start_time = datetime(start_date.year, start_date.month, start_date.day)
            end_time = datetime(start_date.year, start_date.month, start_date.day, 23, 59, 59)
    else:
        raise ValueError(f"Invalid value")
    query = {
        'atime': {
            '$gte': start_time,
            '$lte': end_time
        }}
    for f in tb_analysis_user_data.find(query,{'_id':0}).skip(skip).limit(limit).sort('atime',-1):
        result = tb_module.find_one({'_id':f['oid']})
        if not result:
            raise LookupError("No matching record found in the database.")
        f['widget_type'] = result['widget_type']
        f['thumb_url'] = result['thumb_url']
        f['atime'] = result['atime']
        f['click_rate'] = get_rate_pencent(f['click_count'], f['view_count'])
        f['complete_set_rate'] = get_rate_pencent(f['complete_set_count'], f['click_count'])
        result_list.append(format_data(f))
    return result_list
    
def get_analysis_data(skip:int=0, limit:int=0, start_date:datetime=None, end_date:datetime=None, n:int=7):
    res = []
    if start_date:
        if end_date:
            res = get_data(result_list=res,skip=skip, limit=limit, start_date=start_date, end_date=end_date)
        else:
            res = get_data(result_list=res,skip=skip,limit=limit, start_date=start_date)
    else:
        for f in range(1, n+1): 
            past_day = datetime.now() - timedelta(days=f)
            res = get_data(result_list=res,skip=skip,limit=limit, start_date=past_day)
    return {
            'count': len(res),
            'res':res
        }

